package com.GamersCom.games;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.GamersCom.db.Game;
import com.GamersCom.db.Platform;
import com.GamersCom.model.GameMgr;
import com.GamersCom.model.GenreMgr;
import com.GamersCom.model.MgrFactory;
import com.GamersCom.model.PlatformMgr;
import com.GamersCom.util.GlobalCONST;

/**
 * Servlet implementation class AdminGames
 */
public class AdminGames extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MgrFactory factory = (MgrFactory) this.getServletContext()
				.getAttribute("mgrFactory");
		PlatformMgr pfMgr = factory.getPlatformMgr();
		GenreMgr genreMgr = factory.getGenreMgr();
		GameMgr gameMgr = factory.getGameMgr();

		//retrieve the parameter
		String filter = request.getParameter("filter");
		
		try
		{
			List<Platform> pfList = pfMgr.getAll();
			request.setAttribute("pfList", pfList);	
	
			//get game by platform
			List<Game> gameList;
			if ( filter == null)
			{
				gameList = gameMgr.getAllGames();
			} else if ( filter.equals("all"))
			{
				gameList = gameMgr.getAllGames();
			}
			else 
			{			
				gameList = gameMgr.getAllByPf(filter);
			}
			request.setAttribute("gameList", gameList);
		}
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
						
		String nextView = "/adminGames.jsp";
		request.getRequestDispatcher(nextView).forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Delete action");	
		System.out.println("post submit =>" + request.getParameter("submit"));		
		String submit = request.getParameter("submit");
		MgrFactory factory = (MgrFactory) this.getServletContext()
				.getAttribute("mgrFactory");
		PlatformMgr pfMgr = factory.getPlatformMgr();
		GameMgr gameMgr = factory.getGameMgr();
		
		String nextView = "/adminGames.jsp";
		
		// Delete Action
		if ( submit.equals("Delete")) 
		{
			//retrieve the form data
			int gid = Integer.parseInt(request.getParameter("id"));
			Game game = new Game();
			game.setId(gid);
			
			try
			{
				gameMgr.delete(game);
				request.setAttribute("msg", "Delete successfully!");
			}
			catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
				request.setAttribute("msg", "Error: Delete failed!");
			}						
		}
		
		doGet(request,response);
	}
	
	

}
